﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using RedBit.OAuthLibrary;
using TradeMeSDK;
using TradeMeSDK.OAuthLibrary;

namespace TradeMo
{
    public partial class TradeMeLoginView
    {
        public TradeMeLoginView()
        {
            InitializeComponent();
            Loaded += TradeMeLoginView_Loaded;
            AnimationContext = LayoutRoot;
        }

    	private int _attempts;

        void TradeMeLoginView_Loaded(object sender, RoutedEventArgs e)
        {
            //BrowserProgress.Visibility = Visibility.Visible;

            OAuth.GetRequestToken(
                    TradeMeOAuth.RequestToken,
                    TradeMeOAuth.ConsumerKey,
                    TradeMeOAuth.ConsumerSecret,
                    OnTokenReceived);
        }

        private void OnTokenReceived(object sender, OAuthEventArgs e)
        {
			if (e.IsError)
			{
				if (_attempts == 0)
				{
				}

				_attempts++;
				TradeMeDispatcher.OnUIThread(() =>
				        {
				        	MessageBox.Show("Bugger: Unable to logon to trademe at the moment.  Please try again later");
							NavigationService.GoBack();
				        });
				return;
			}
        	Dictionary<string, string> result = Helpers.ParseQueryString(e.Response);
            TradeMeOAuth.Token = result["oauth_token"];
            TradeMeOAuth.TokenSecret = result["oauth_token_secret"];

            TradeMeDispatcher.OnUIThread(() =>
            {
                TmBrowser.Visibility = Visibility.Visible;
                TmBrowser.Navigate(new Uri(TradeMeOAuth.Authorize));
            });
        }

        private void TmBrowser_Navigating(object sender, NavigatingEventArgs e)
        {
            //BrowserProgress.Visibility = Visibility.Visible;
        }

        private void TmBrowser_Navigated(object sender, NavigationEventArgs e)
        {
            //BrowserProgress.Visibility = Visibility.Collapsed;
            string addr = e.Uri.ToString();
            if (addr.Contains("oauth_verifier")) //Is user authenticated?
            {
                TmBrowser.Visibility = Visibility.Collapsed;
                Dictionary<string, string> query = Helpers.ParseQueryString(e.Uri.Query);
                TradeMeOAuth.Verifier = query["oauth_verifier"];
                TradeMeDispatcher.OnUIThread(() => TradeMeOAuth.BeginGetToken(OnTokenReceived));
            }
        }

        //Ticked ok, let's go to the hub
        private void OnTokenReceived(object sender, EventArgs args)
        {
            TradeMeDispatcher.OnUIThread(() => NavigationService.GoBack());
        }

    }
}